/***********************************************************************************************
 * Copyright (C) 2022 China Southern Power Grid Shenzhen Digital Grid Research Institute Co.,Ltd
 * All Rights Reserved.
 * 本软件为南方电网深圳数字电网研究院有限公司开发研制。
 * 未经本公司正式书面同意，其他任何个人、团体不得使用、复制、修改或发布本软件。
 ***********************************************************************************************/

package com.lrj.email;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * @version 10月 11, 2023
 * @since JDK1.8
 */
public class EmailUtil {
    public static Session createSession(String userName, String password) {
        Properties pros = new Properties();
        pros.put("mail.smtp.host", "smtp.qq.com");
        pros.put("mail.smtp.auth", "true");
        pros.put("mail.smtp.starttls.enable", "true");

        //创建Session
        Session session = Session.getInstance(pros, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(userName, password);
            }
        });
        session.setDebug(true);
        return session;
    }

    public static void send(String userName, String password, String recipientEmail, String subject, String content) throws MessagingException {
        Session session = createSession(userName, password);
        System.out.println(session);

        //2.创建邮件对象
        MimeMessage message = new MimeMessage(session);
        //设置邮件主题
        message.setSubject(subject);
        //设置邮件内容
        message.setText(content);
        //设置发件人
        message.setFrom(new InternetAddress(userName));
        //设置收件人
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipientEmail));

        //3.发送邮件
        Transport.send(message);
    }
}
